from wxauto import WeChat
from chat import Chat
import pickle
import time
import json
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
from config import chat_config
class app():
    def __init__(self):
        self.wx = WeChat()
        self.chat = Chat()
        try:
            with open('savedata.json', 'r') as f:
                self.userdata = json.load(f)
        except:
            self.userdata = {}
            with open('savedata.json', 'w', encoding='utf-8') as f:
                json.dump(self.userdata, f, ensure_ascii=False, indent=4)
        self.looptime = chat_config['loop_time']
    def wait(self):
        logging.info("looping...")
        with open('savedata.json', 'w', encoding='utf-8') as f:
            json.dump(self.userdata, f, ensure_ascii=False, indent=4)
        time.sleep(self.looptime)
    def run(self):
        while True:
            msgs = self.wx.GetNextNewMessage(savevoice=True)
            if msgs=={}:
                self.wait()
                continue
            print(msgs)
            for name in msgs:
                text =''
                for msg in msgs[name]:
                    if msg.type!='friend':
                        continue
                    msg=msg.info
                    if msg[0]=='Self':
                        continue
                    elif  msg[1]=='[文件]'or msg[1]=='[图片]':
                        self.wx.SendMsg("暂不支持文件和图片",who=name)
                        continue
                    else:
                        text += msg[1]
                    print(text)
                if text== "":
                    logging.warning("null message")
                    continue
                if name in self.userdata:
                    logging.info('user: '+name+'message: '+text)
                    text = self.chat.send_message(text, self.userdata[name])
                else:
                    logging.info('new user: '+name)
                    self.userdata[name]=self.chat.create_chat(name)
                    logging.info('getuserid: '+self.userdata[name])
                    text = self.chat.send_message(text, self.userdata[name])
                logging.info('chatbot: '+text)
                self.wx.SendMsg(text,who=name)
            self.wait()



if __name__ == '__main__':
    print("因为chatgpt没有额度，所以该代码改成使用通义千问的接口进行聊天。")
    print("有四个文件，main.py是主程序，chat.py是聊天模块，config.py是配置文件，savedata.json是保存用户的对话信息的线程id。")
    print("使用了Assistant API ，可以为每个微信好友单独添加一个线程进行聊天。")
    print("运行main.py即可，第三方库wxauto和dashscope")
    print("千问的apikey也跟您留着了，您可以直接运行")
    print("阿里那里的联网和绘图需要申请权限，所以暂时无法使用。")
    try:
        app = app()
    except ModuleNotFoundError as e:
        print("请使用'pip install requirements.txt'安装依赖")
    except Exception as e:
        print(e)
    logging.info("start")
    app.run()